#include "LayerParser.h"
#include "..\utils\Log.h"
#include "..\utils\PlainTextReader.h"
#include "..\base\Engine.h"
#include "..\game\World.h"

namespace ds {

ResourceDeclaration* LayerParser::loadTextFile(const ResourceFile& resourceFile) {
	JSONReader reader;
	if ( reader.parse(resourceFile.fqName.c_str()) ) {
		std::vector<Category*> all = reader.getCategories();
		if ( all.size() > 0 ) {
			Category* root = all[0];
			if ( root->getName() == "layers" ) {
				WorldDecl* wd = new WorldDecl;
				std::vector<Category*> categories = root->getChildren();
				for ( size_t i = 0; i < categories.size(); ++i ) {
					Category* cat = categories[i];
					if ( cat->getName() == "layer" ) {
						if ( cat->hasProperty("name") ) {					
							std::string name = cat->getProperty("name");
							bool active = cat->getBool("active",true);					
							LayerDecl* ld = new LayerDecl(name,active);
							wd->addLayerDecl(ld);
						}
						else {
							LOGC(logERROR,"LayerParser") << "missing name property detected";
						}
					}
				}
				return wd;
			}
			else {
				LOGC(logERROR,"LayerParser") << "First category must be 'layers' - skipping file";
			}
		}
		else {
			LOGC(logERROR,"LayerParser") << "No layers category found in file - skipping file";
		}
	}
	return 0;
}
/*
ResourceDeclaration* LayerParser::loadTextFile(const ResourceFile& resourceFile) {
	PlainTextReader reader;
	if ( reader.readFile(resourceFile.fqName.c_str()) ) {
		Category* root = reader.getRoot();
		WorldDecl* wd = new WorldDecl;
		std::vector<Category*> categories = root->getChildren();
		for ( size_t i = 0; i < categories.size(); ++i ) {
			Category* cat = categories[i];
			if ( cat->getName() == "layer" ) {
				if ( cat->hasProperty("name") ) {					
					std::string name = cat->getProperty("name");
					bool active = cat->getBool("active",true);					
					LayerDecl* ld = new LayerDecl(name,active);
					wd->addLayerDecl(ld);
				}
				else {
					LOGC(logERROR,"LayerParser") << "missing name property detected";
				}
			}
		}
		return wd;
	}
	return 0;
}
*/
void LayerParser::createResource(ResourceDeclaration* declaration) {
	WorldDecl* wd = static_cast<WorldDecl*>(declaration);
	for ( size_t i = 0; i < wd->size();++i ) {
		LayerDecl* ld = wd->get(i);
		WorldLayer wl = gEngine->getWorld().createLayer(ld->getName().c_str());
		if ( ld->isActive() ) {
			gEngine->getWorld().activateLayer(wl);			
		}
		else {
			gEngine->getWorld().deactivateLayer(wl);
		}
	}
}
/*
bool LayerParser::readBinary(PAKReader& reader) {
	std::string name = reader.readString();
	bool active = reader.readBool();
	LOG(logINFO) << "layer " << name << " active " << active;
	WorldLayer wl = gEngine->getWorld().createLayer(name.c_str());
	if ( !active ) {
		gEngine->getWorld().deactivateLayer(wl);
	}
	else {
		gEngine->getWorld().activateLayer(wl);
	}
	return true;
}
*/
}
